package com.example.redis_demo;

import java.util.concurrent.*;

public class ThreadPoolSingleton {

    private static volatile ThreadPoolSingleton instance;
    private final ExecutorService executorService;

    private ThreadPoolSingleton() {
        int availableProcessor = Runtime.getRuntime().availableProcessors();
        int coreNum = availableProcessor / 2;

        // 用单例模式创建线程池，保留2个核心线程，最多线程为CPU个数的2n+1的两倍.
        int maxProcessor = (availableProcessor * 2 + 1) * 2;

        executorService = new ThreadPoolExecutor(Math.min(coreNum, 2), maxProcessor,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<>());
    }

    public static ThreadPoolSingleton getInstance() {
        if (instance == null) {
            synchronized (ThreadPoolSingleton.class) {
                if (instance == null) {
                    instance = new ThreadPoolSingleton();
                }
            }
        }
        return instance;
    }

    public void executeTask(Runnable runnable) {
        executorService.execute(runnable);
    }

    /**
     * 这个方法可根据你的需要添加
     */
    public <T> Future<T> submit(Runnable task, T result) {
        return executorService.submit(task, result);
    }

    /**
     * 这个方法可根据你的需要添加
     */
    public Future<?> submit(Runnable task) {
        return executorService.submit(task);
    }
}